#include "narrationnode.h"
#include <QDebug>
#include "GameData/jsontranslator.h"
#include "ResourceManger/filemanager.h"
NarrationNode::NarrationNode()
{
    this->id = GameData::Instance().curRegisterNodeId;
    GameData::Instance().curRegisterNodeId ++;
    NarrationTree::Instance().AddNode(this);
}

NarrationNode::NarrationNode(const NarrationNode &node)
{
    this->id = GameData::Instance().curRegisterNodeId;
    GameData::Instance().curRegisterNodeId ++;
    NarrationTree::Instance().AddNode(this);

    //不复制linker和分支
    for(int i = 0;i < node.image.count();i++)
    {
        if(node.image[i])
        {
            RenderTarget* rt = new RenderTarget(*node.image[i]);
            this->image.push_back(rt);
        }
    }
    if(node.bgm)
        this->bgm = new BGM(*node.bgm);
    if(node.bgse)
        this->bgse = new BGM(*node.bgse);

    this->nodeName = node.nodeName;
    this->stopBgm = node.stopBgm;
    this->stopBgse = node.stopBgse;
    this->soundPath = node.soundPath;
    this->name = node.name;
    this->text = node.text;
    this->effect = node.effect;
    this->effectName = node.effectName;
}

NarrationNode::~NarrationNode()
{
    delete bgm;
    delete bgse;
    while(image.count() > 0)
    {
        RenderTarget* tmp = image.at(image.count() - 1);
        image.pop_back();
        delete tmp;
    }
    while(linkers.count() > 0)
    {
        Linker* linker = linkers.at(linkers.count() - 1);
        linkers.pop_back();
        delete linker;
    }
}

bool NarrationNode::RemoveLinkerAt(int index)
{
    if(index < 0 || index >= linkers.count())
        return false;
    Linker* linker = linkers.at(index);
    linkers.removeAt(index);
    delete linker;
    return true;
}

void NarrationNode::RemoveImage(int layer)
{
    for(int i = 0;i < image.count();i++)
    {
        if(image[i]->GetLayer() == layer)
        {
            RenderTarget* rt = image[i];
            delete rt;
            rt = nullptr;
            image.remove(i);
            break;
        }
    }
}

NarrationTree &NarrationTree::Instance()
{
    static NarrationTree instance;
    return instance;
}

NarrationTree::~NarrationTree()
{

}

void NarrationTree::AddNode(NarrationNode *node)
{
    narrationTree.insert(node->id,node);
}

NarrationNode* NarrationTree::InitTree()
{
    //读取节点
    JsonTranslator jt;
    QJsonObject* ob = FileManager::Instance().ReadJsonFile(FileManager::Instance().nodeTreePath);
    if(ob)
    {
        QJsonArray array = (*ob)["narrationNodeTree"].toArray();

        NarrationNode* root = nullptr;
        for(int i = 0;i < array.count();i++)
        {
            QJsonObject ob = array[i].toObject();
            NarrationNode* node = jt.NodeFromJson(&ob);
            if(node && node->parentId < 0)
                root = node;
            if(node)
                narrationTree.insert(node->id,node);
        }
        if(root)
            return root;
    }
    //如果没有节点，则初始化：创建空白根节点
    NarrationNode* node = new NarrationNode();
    AddNode(node);
    return node;
}

void NarrationTree::SaveTree()
{
    JsonTranslator jt;
    QString path = FileManager::Instance().nodeTreePath;
    QJsonArray *array = new QJsonArray();
    QVector<QJsonObject*> obs;
    for(auto it = narrationTree.begin();it != narrationTree.end();it++)
    {
        if(!it.value())
            continue;
        QJsonObject* ob = jt.ToJson(it.value());
        if(!ob)
            continue;
        array->append(*ob);
        obs.push_back(ob);
    }
    QJsonObject* ob = new QJsonObject();
    ob->insert("narrationNodeTree",*array);
    FileManager::Instance().Write(path,jt.Json2Byte(ob));
    //清理内存
    delete ob;
    ob = nullptr;

    for(int i = 0;i < obs.count();i++)
    {
        delete obs[i];
        obs[i] = nullptr;
    }
    obs.clear();
}

void NarrationTree::DeleteNode(int id)
{
    //整理父子关系
    if(!narrationTree.contains(id) || !narrationTree[id])
        return;
    if(narrationTree.contains(-1))
        narrationTree.remove(-1);
    int cid = narrationTree[id]->childId;
    int pid = narrationTree[id]->parentId;
    //分类处理
    //1有子节点和父节点，不是分支
    if(cid*pid >= 0 && narrationTree.contains(cid) && narrationTree.contains(pid) && narrationTree[pid]->childId == id)
    {
        qDebug()<<"1有子节点和父节点，不是分支";
        narrationTree[cid]->parentId = pid;
        narrationTree[pid]->childId = cid;
    }
    //2有子节点和父节点，是分支
    if(cid >= 0 && pid >= 0 && narrationTree.contains(cid) && narrationTree.contains(pid) && narrationTree[pid]->childId != id)
    {
        qDebug()<<"2有子节点和父节点，是分支";
        narrationTree[cid]->parentId = pid;
        NarrationNode* pnode = narrationTree[pid];
        for(int i = 0;i < pnode->linkers.count();i++)
        {
            if(pnode->linkers[i]->branchId == id)
            {
                pnode->linkers[i]->branchId = cid;
            }
            if(pnode->linkers[i]->cycleId == id)
            {
                pnode->linkers[i]->cycleId = cid;
            }
        }
    }
    //3有子节点无父节点
    if(pid < 0 && cid >= 0 && narrationTree.contains(cid) && !narrationTree.contains(pid))
    {
        qDebug()<<"3有子节点无父节点";
        narrationTree[cid]->parentId = -1;
    }
    //4无子节点有父节点，是分支
    if(pid >= 0 && cid < 0 && !narrationTree.contains(cid) && narrationTree.contains(pid) && narrationTree[pid]->childId != id)
    {
        qDebug()<<"4无子节点有父节点，是分支";
        NarrationNode* pnode = narrationTree[pid];
        for(int i = 0;i < pnode->linkers.count();i++)
        {
            if(pnode->linkers[i]->branchId == id)
            {
                pnode->linkers[i]->branchId = -1;
            }
            if(pnode->linkers[i]->cycleId == id)
            {
                pnode->linkers[i]->cycleId = -1;
            }
        }
    }
    //5无子节点有父节点，不是分支
    if(!narrationTree.contains(cid) && narrationTree.contains(pid) && narrationTree[pid]->childId == id)
    {
        qDebug()<<"5无子节点有父节点，不是分支";
        narrationTree[pid]->childId = -1;
    }
    //6无子节点无父节点，说明只剩这一个节点，不进行处理
}

NarrationTree::NarrationTree()
{
}
